package com.example.designpattern.behavioral.command;

import com.example.designpattern.behavioral.command.command.*;
import com.example.designpattern.behavioral.command.component.Door;
import com.example.designpattern.behavioral.command.component.Light;
import com.example.designpattern.behavioral.command.component.Music;
import com.example.designpattern.behavioral.command.component.Tv;
import org.junit.Test;

import java.util.Stack;

public class Client {

    // 所有的命令
    Stack<ICommand> commands = new Stack<>();

    @Test
    public void test() {
        // 初始化智能家居设备和命令
        Door door = new Door();
        Light light = new Light();
        Tv tv = new Tv();
        Music music = new Music();

        DoorOpenCommand doorOpenCommand = new DoorOpenCommand(door);
        DoorCloseCommand doorCloseCommand = new DoorCloseCommand(door);
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        LightOffCommand lightOffCommand = new LightOffCommand(light);
        TvOnCommand tvOnCommand = new TvOnCommand(tv);
        TvOffCommand tvOffCommand = new TvOffCommand(tv);
        MusicPlayCommand musicPlayCommand = new MusicPlayCommand(music);
        MusicStopCommand musicStopCommand = new MusicStopCommand(music);

        // 模拟开关操作
        handleCommand(true, doorOpenCommand, doorCloseCommand);
        handleCommand(false, lightOnCommand, lightOffCommand);

        // 撤销上一个命令
        if (!commands.isEmpty()) {
            ICommand lastCommand = commands.pop();
            lastCommand.undo();
        }
    }

    private void handleCommand(boolean isChecked, ICommand openCommand, ICommand closeCommand) {
        if (isChecked) {
            commands.push(openCommand);
            openCommand.execute();
        } else {
            commands.push(closeCommand);
            closeCommand.execute();
        }
    }
}
